﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace testCl
{
    class Program
    {
        static void Main(string[] args)
        {
            String id;
            id = System.Console.ReadLine();//tutaj podaje id
            new cl(id);//tworze kleinta z tym id
            while (true)
            {
                String info;
                info = Console.ReadLine();
            }
        }
    }

    class cl
    {
        void send()
        {
            //mozna dorobic senda asyn :PP
        }
        private String Id;
        public cl(String Id)
        {
            this.Id = Id;
            OnConnect();//Podlaczam klienta
        }

        byte[] m_DataBuffer = new byte[10];
        IAsyncResult m_asynResult;
        public AsyncCallback pfnCallBack;
        public Socket m_socClient;
        // create the socket...
        public void OnConnect()
        {
            m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // get the remote IP address...
            IPAddress ip = IPAddress.Parse("127.0.0.1");//ip serwera
            int iPortNo = 8221;//port serwera
            //create the end point
            IPEndPoint ipEnd = new IPEndPoint(ip.Address, iPortNo);
            //connect to the remote host...
            m_socClient.Connect(ipEnd);//podlaczam sie do serwera
            byte[] byData = System.Text.Encoding.ASCII.GetBytes(Id);//wysylam na serwer wiadomosc ze swoim Id
            m_socClient.BeginSend(byData, 0, byData.Length, SocketFlags.None, null, null);//wysylam
            //watch for data ( asynchronously )...
            WaitForData();//czekam na dane od serwera
        }
        public void WaitForData()//standard
        {
            if (pfnCallBack == null)
                pfnCallBack = new AsyncCallback(OnDataReceived);
            // now start to listen for any data...
            m_asynResult =
            m_socClient.BeginReceive(m_DataBuffer, 0, m_DataBuffer.Length, SocketFlags.None, pfnCallBack, null);
        }
        public void OnDataReceived(IAsyncResult asyn)//standard
        {
            //end receive...
            int iRx = 0;
            iRx = m_socClient.EndReceive(asyn);
            char[] chars = new char[iRx + 1];
            System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
            int charLen = d.GetChars(m_DataBuffer, 0, iRx, chars, 0);
            System.String szData = new System.String(chars);
            System.Console.WriteLine(szData);
            System.Console.WriteLine(Id);
            WaitForData();
        }
    }
}
